package com.vitogiovanni.tobook;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.vitogiovanni.tobook.entity.prenotazioneendpoint.Prenotazioneendpoint;
import com.vitogiovanni.tobook.entity.prenotazioneendpoint.model.Prenotazione;
import com.vitogiovanni.tobook.utilities.CustomTimePickerDialog;
import com.vitogiovanni.tobook.utilities.DatePickerFragment;
import com.vitogiovanni.tobook.utilities.NetworkChecker;
import com.vitogiovanni.tobook.utilities.UserEmailFetcher;

public class PrenotaActivity extends FragmentActivity {
	
	
	private Activity thisActivity;
	private TextView mDateDisplay;
	private TextView mTimeDisplay;
	private TextView titleDisplay;
	private EditText numPosti;
	private EditText nomePrenot;
	private EditText notePrenot;
    private Button mPickDate;
    private Button mPickTime;
    private Button numPostiButton;
    private Button nomePrenotButton;
    private Button notePrenotButton;
    private ActionBar actionBar;
    
    private String errore;

    private PrenotazioneTask prenotazioneTask;
    private Button prenotaButton;
    
    private String localeId;
    private String date;
    private String ora;
    private int numeroPosti = 0;
    private String nominativo;
    private String note;
    private Date data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		thisActivity = this;
		setContentView(R.layout.activity_prenota);
		
		Bundle bundle = getIntent().getExtras();
		String nomeLocale = (String) bundle.get("localeId");
		localeId = (String) bundle.get("localeKey");		
		
		actionBar = getActionBar();
		actionBar.setTitle(nomeLocale);
		
		titleDisplay = (TextView) findViewById(R.id.textview_titololocale_prenota);
		mDateDisplay = (TextView) findViewById(R.id.textview_date_prenota);
		mTimeDisplay = (TextView) findViewById(R.id.textview_time_prenota);
		numPosti = (EditText) findViewById(R.id.textview_numero_posti_prenota);
		nomePrenot = (EditText) findViewById(R.id.textview_nominativo_prenota);
		notePrenot = (EditText) findViewById(R.id.textview_note_prenota);
		
		mPickDate = (Button) findViewById(R.id.button_date_prenota);
        mPickTime = (Button) findViewById(R.id.button_time_prenota);
        numPostiButton = (Button) findViewById(R.id.button_numero_posti_prenota);
        nomePrenotButton = (Button) findViewById(R.id.button_nominativo_prenota);
        notePrenotButton = (Button) findViewById(R.id.button_note_prenota);

        prenotaButton = (Button) findViewById(R.id.button_prenota_locale);
        
        
        titleDisplay.setText(getResources().getString(R.string.messaggio_compilazione_form_prenota) + " " + nomeLocale);
        
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDatePicker();
            }
        });	
        
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	CustomTimePickerDialog timePickerDialog = new CustomTimePickerDialog(PrenotaActivity.this, timeSetListener, 
                        Calendar.getInstance().get(Calendar.HOUR), 
                        CustomTimePickerDialog.getRoundedMinute(Calendar.getInstance().get(Calendar.MINUTE) + CustomTimePickerDialog.TIME_PICKER_INTERVAL), true);
            	timePickerDialog.setTitle("Selezionare l'ora ed i minuti");
            	timePickerDialog.show();
            }
        });
        
        numPostiButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				numPosti.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(numPosti, InputMethodManager.SHOW_IMPLICIT);
			}
		});
        
        nomePrenotButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				nomePrenot.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(nomePrenot, InputMethodManager.SHOW_IMPLICIT);
			}
		});

        notePrenotButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				notePrenot.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(notePrenot, InputMethodManager.SHOW_IMPLICIT);
			}
		});
        
        prenotaButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				View currentView = thisActivity.getCurrentFocus();
			    if(currentView!=null)
				{
			    	imm.hideSoftInputFromWindow(currentView.getWindowToken(),0);
				}
				
				if (!NetworkChecker.isInternetAvailable(PrenotaActivity.this)) {
					NetworkChecker.noConnectionToast(PrenotaActivity.this);
					return;
				}
				errore = "";
				date = mDateDisplay.getText().toString();
				ora = mTimeDisplay.getText().toString();

				if(!date.equals("") && !ora.equals("")){	
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
					try {
						String dateToParse = date + " " + ora;
						data = formatter.parse(dateToParse);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				
				if(!numPosti.getText().toString().equals("")){
					numeroPosti = Integer.valueOf(numPosti.getText().toString());
				}
				
				nominativo = nomePrenot.getText().toString();
				note = notePrenot.getText().toString();
				
				if(numeroPosti != 0 && !nominativo.equals("") && !date.equals("") && !ora.equals("")){					
					prenotazioneTask = (PrenotazioneTask) new PrenotazioneTask();
					prenotazioneTask.execute();
				}
				else{
					Toast.makeText(getApplicationContext(), getResources().getString(R.string.messaggio_riempimento_form_prenota), Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		
	}
	
	private void showDatePicker() {
		  DatePickerFragment date = new DatePickerFragment();
		  /**
		   * Set Up Current Date Into dialog
		   */
		  Calendar calender = Calendar.getInstance();
		  Bundle args = new Bundle();
		  args.putInt("year", calender.get(Calendar.YEAR));
		  args.putInt("month", calender.get(Calendar.MONTH));
		  args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
		  date.setArguments(args);
		  /**
		   * Set Call back to capture selected date
		   */
		  date.setCallBack(ondate);
		  date.show(getSupportFragmentManager(), "Date Picker");
	}

	OnDateSetListener ondate = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			
			mDateDisplay.setText(String.valueOf(year) + "-" + String.valueOf(monthOfYear+1)
							+ "-" + String.valueOf(dayOfMonth));
		}	
	};
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.prenota, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	*/
  
	private CustomTimePickerDialog.OnTimeSetListener timeSetListener = new CustomTimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        	mTimeDisplay.setText(String.format("%02d", hourOfDay) + ":" +String.format("%02d", minute));
        }
	};
	
	private class PrenotazioneTask extends AsyncTask<Void, Void, Prenotazione> {

		private ProgressBar progressBar = (ProgressBar) findViewById(R.id.loading_prenota_locale_activity);
		
		@Override
		protected void onPreExecute(){
			progressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Prenotazione doInBackground(Void... params) {

			Context context = getApplicationContext();
			CharSequence text = UserEmailFetcher.getEmail(context);
			
			Prenotazioneendpoint.Builder builder1 = new Prenotazioneendpoint.Builder(
					AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
					null);
			builder1 = CloudEndpointUtils.updateBuilder(builder1);
			builder1.setApplicationName("to-book");
			Prenotazioneendpoint endpointPrenotazione = builder1.build();
			Prenotazione prenotazioneGet = new Prenotazione();
			
			try{
				prenotazioneGet = endpointPrenotazione.prenota((long)7200000, localeId, text.toString(), nominativo, note, numeroPosti, data.getTime()).execute();
			}catch(IOException e){
				errore = getMsgFromJson(e.getMessage());
			}
			return prenotazioneGet;
		}
		
		@Override
		protected void onPostExecute(Prenotazione result) {
			
			if(errore.equals(""))
			{
				progressBar.setVisibility(View.GONE);
				
				Intent returnIntent = new Intent();
				returnIntent.putExtra("data", data.getTime());
				returnIntent.putExtra("numeroPersone", numeroPosti);
				setResult(RESULT_OK, returnIntent);        
				finish();
			}
			else{
				progressBar.setVisibility(View.GONE);
				
				Toast.makeText(getApplicationContext(), errore, Toast.LENGTH_SHORT).show();
			}
		}
		
		private String getMsgFromJson(String json)
		{
			int messagePosition = json.indexOf("\"message\""); 
			String message;
			message = json.substring(messagePosition+13, json.indexOf("\"", messagePosition+13));
			
			return message;
		}
	}
}

